//
//  SQBWithdrawViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/7.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "SQBWithdrawViewController.h"

@interface SQBWithdrawViewController ()<HTTPClientDelegate> {
    NSString *_bankIdStr;
    BOOL _payPasswordStatus;
    
    BOOL _isBalanceSelect;

    NSString *_bankId;
    // balance-账户可提现金额
    double  _balance;
    // balance3-随取宝可提现金额
    double _balance3;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView       *bankInfoBackView;
@property (weak, nonatomic) IBOutlet UIImageView  *logoImageView;
@property (weak, nonatomic) IBOutlet UILabel      *bankNameLabel;
@property (weak, nonatomic) IBOutlet UILabel      *bankNumLabel;
@property (weak, nonatomic) IBOutlet UILabel      *amoutValue;
@property (weak, nonatomic) IBOutlet UITextField  *amoutTextField;
@property (weak, nonatomic) IBOutlet UILabel      *moneyTypeValue;
@property (weak, nonatomic) IBOutlet ClickButton  *withdrawButton;
@property (weak, nonatomic) IBOutlet UILabel *tradePwdValue;
@property (weak, nonatomic) IBOutlet UITextField  *tradePwdTextField;
@property (weak, nonatomic) IBOutlet UIButton     *balanceButton;
@property (weak, nonatomic) IBOutlet UIButton     *sqbButton;
@property (weak, nonatomic) IBOutlet UILabel      *remindLabel;

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) BOOL          isLoading;
@property (nonatomic, assign) NSInteger     requestType;

@end

@implementation SQBWithdrawViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self initNavBarTitle:@"提现" andLeftItemName:@"返回" andRightItemName:@""];
    
    [self initData];
    [self initView];
}
- (IBAction)withdrawButtonClick:(id)sender {
    
    if (_amoutTextField.text.doubleValue <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的金额"];
        return;
    }
    if (_amoutTextField.text.doubleValue < 100) {
        [SVProgressHUD showErrorWithStatus:@"最低提现金额不能小于100元"];
        return;
    }
    if (_tradePwdTextField.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入交易密码"];
        return;
    }
    
    [self withdrawRequest];
}

- (IBAction)balanceButtonClick:(id)sender {
    _isBalanceSelect = YES;
    _amoutTextField.placeholder = [NSString stringWithFormat:@"本次可提现金额%.2f",_balance];
    _balanceButton.selected = YES;
    _sqbButton.selected = NO;
}
- (IBAction)sqbButtonClick:(id)sender {
    _isBalanceSelect = NO;
    _amoutTextField.placeholder = [NSString stringWithFormat:@"本次可提现金额%.2f",_balance3];
    _balanceButton.selected = NO;
    _sqbButton.selected = YES;
}

- (void)changeValue:(UITextField *)textField {
    
    if (_amoutTextField.text.length > 0 && _tradePwdTextField.text.length>0) {
        [CommonClass buttonEnableWithButton:_withdrawButton enable:YES];
    }else {
        [CommonClass buttonEnableWithButton:_withdrawButton enable:NO];
    }
}
#pragma mark - 初始化请求
- (void)initData {
    _isBalanceSelect = NO;
    
    [self requestData];
}

- (void)requestData {
    if (AppDelegateInstance.userInfo==nil) {
        [ReLogin goLogin:self];
        return;
    }
    _requestType = 1;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"145" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters withViewController:self];
}

- (void)withdrawRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍后再试"];
        return;
    }
    [CommonClass buttonEnableWithButton:_withdrawButton enable:NO];
    
    if (_isBalanceSelect) {
        _requestType = 2;
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:@"144" forKey:@"OPT"];
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
        [parameters setObject:_amoutTextField.text forKey:@"amount"];
        [parameters setObject:_bankIdStr forKey:@"bankId"];
        [parameters setObject:@"1" forKey:@"type"];
        [parameters setObject:[NSString encrypt3DES:_tradePwdTextField.text key:DESkey] forKey:@"payPassword"];
        
        if (_requestClient == nil) {
            _requestClient = [[NetWorkClient alloc] init];
            _requestClient.delegate = self;
        }
        [_requestClient requestGet:@"app/services" withParameters:parameters];
    }else {
        _requestType = 3;
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:@"521" forKey:@"OPT"];
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
        [parameters setObject:_amoutTextField.text forKey:@"amount"];
        [parameters setObject:_bankIdStr forKey:@"bankId"];
        [parameters setObject:@"2" forKey:@"type"];
        [parameters setObject:[NSString encrypt3DES:_tradePwdTextField.text key:DESkey] forKey:@"payPassword"];
        
        if (_requestClient == nil) {
            _requestClient = [[NetWorkClient alloc] init];
            _requestClient.delegate = self;
        }
        [_requestClient requestGet:@"app/services" withParameters:parameters];
    }
    
}

//HTTPClientDelegate
-(void) startRequest
{
    _isLoading = YES;
}

-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj
{
    _isLoading = NO;
    if (_requestType == 2) {
        [CommonClass buttonEnableWithButton:_withdrawButton enable:YES];
    }
    NSDictionary *dics=(NSDictionary *)obj;
    DLOG(@"dic=%@",dics);
    
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        _balance = [dics[@"balance"] doubleValue];
        _balance3 = [dics[@"balance3"] doubleValue];
        _amoutTextField.placeholder = [NSString stringWithFormat:@"本次可提现金额%.2f",_balance3];
        NSArray *bankList = dics[@"bankList"];
        if (bankList.count) {
            NSDictionary *dataDict = bankList[0];
            NSString *bankNameStr = [NSString stringWithFormat:@"%@",dataDict[@"bankName"]];
            NSString *bankNumStr = [NSString stringWithFormat:@"%@",dataDict[@"account"]];
            _bankIdStr = [NSString stringWithFormat:@"%@",dataDict[@"id"]];
            
            _bankNumLabel.text = [NSString stringWithFormat:@"尾号%@",[bankNumStr substringFromIndex:bankNumStr.length-4]];
//            _payWayLabel.text = [NSString stringWithFormat:@"%@ (%@)",bankNameStr,[bankNumStr substringFromIndex:bankNumStr.length-4]];
            
             _bankNameLabel.text = [CommonClass setBankLogoImageWithBankName:bankNameStr imageView:_logoImageView ];
            // _bankNameLabel.text = bankNameStr;

            
        }else if (_requestType==2 || _requestType==3) {
            
//            AppDelegateInstance.isUpdateAccount = YES;
            
            [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else{
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
}

-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error
{
    _isLoading = NO;
    if (_requestType == 2) {
        [CommonClass buttonEnableWithButton:_withdrawButton enable:YES];
    }

    
}

-(void) networkError {
    _isLoading = NO;
    if (_requestType == 2) {
        [CommonClass buttonEnableWithButton:_withdrawButton enable:YES];
    }

}



- (void)initView {
    _bankNameLabel.font = KFontSize(13);
    _bankNumLabel.font = KFontSize(13);
    _amoutValue.font = KFontSize(14);
    _amoutTextField.font = KFontSize(14);
    _moneyTypeValue.font = KFontSize(14);
    _tradePwdValue.font = KFontSize(14);
    _tradePwdTextField.font = KFontSize(14);
    _sqbButton.titleLabel.font = KFontSize(15);
    _balanceButton.titleLabel.font = KFontSize(15);
    _withdrawButton.titleLabel.font = KFontSize(15);
    _remindLabel.font = KFontSize(14);
    
    _withdrawButton.clipsToBounds = YES;
    _withdrawButton.layer.cornerRadius = kCornerRadius;
    [_amoutTextField addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventEditingChanged];
    [_tradePwdTextField addTarget:self action:@selector(changeValue:) forControlEvents:UIControlEventEditingChanged];
    
    NSString *mindStr = [NSString stringWithFormat:@"%@",@"*转账提示：\n1.转入和转出均免手续费。\n\n2.转出最快1分钟到账，部分银行将在2小时内到账。如遇到银行系统升级，请关注网站公告，耐心等待。单日累计5万元内(包含5万)T+0日到账，5万以上T+2日到账。\n\n3.为防止快进快出，用户资金转入后，均需满足最少24小时。\n\n4.严禁非法套现行为，一经发现将终止该账户的使用！"];
    CGFloat mindHeight = [MyTools getSizeOfString:mindStr maxWidth:MSWIDTH - 20 maxHeight:1000 withFontSize:14].height + 5;
    CGRect frame = _remindLabel.frame;
    frame.size.height = mindHeight;
    _remindLabel.frame = frame;
    _remindLabel.attributedText = [MyTools getNSMutableAttributedStringWithText:mindStr start:0 end:1 textColor:KColor textFont:KFontSize(14)];
    
    _scrollView.contentSize = CGSizeMake(0, GetMaxY(_remindLabel) + 50);
}

- (void)viewDidLayoutSubviews {
    CGRect frame = _remindLabel.frame;
    frame.origin.y = GetMaxY(_withdrawButton) + KAdaptNum(16);;
    _remindLabel.frame = frame;
    
    _scrollView.contentSize = CGSizeMake(0, GetMaxY(_remindLabel) + 50);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
